package com.miracle9.game.service;

import com.miracle9.game.bean.DeskGameType;
import com.miracle9.game.bean.DeskUserSession;
import com.miracle9.game.bean.GameTypeSession;
import com.miracle9.game.bean.UserGameTypeSession;
import com.miracle9.game.dao.*;
import com.miracle9.game.entity.Admin;
import com.miracle9.game.entity.AdminLog;
import com.miracle9.game.entity.Notice;
import com.miracle9.game.entity.User;
import com.miracle9.game.enums.GameTypeEnums;
import com.miracle9.game.server.message.AmfMessageSend;
import com.miracle9.game.server.message.MessageSend;
import com.miracle9.game.server.message.StorageMethodEntity;
import com.miracle9.game.util.GameParameterAssist;
import com.miracle9.game.util.MyUtil;
import com.miracle9.game.util.SessionUtils;
import org.apache.mina.core.session.IoSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("noticeService")
public class NoticeService extends BaseService {

    @Autowired
    private NoticeServiceDao noticeServiceDao;
    @Autowired
    private UserServiceDao userServiceDao;
    @Autowired
    private com.miracle9.game.dao.AdminServiceDao adminServiceDao;
    @Autowired
    private com.miracle9.game.dao.AdminLogServiceDao adminLogServiceDao;
    @Autowired
    private DeskServiceDao deskServiceDao;
    @Autowired
    private FishDeskServiceDao fishDeskServiceDao;
    @Autowired
    private CardDeskServiceDao cardDeskServiceDao;
    @Autowired
    private com.miracle9.game.dao.BulletFishDeskServiceDao bulletFishDeskServiceDao;
    @Autowired
    private MermaidDeskServiceDao mermaidDeskServiceDao;
    @Autowired
    private LackDeskServiceDao lackDeskServiceDao;
    @Autowired
    private JoyDeskServiceDao joyDeskServiceDao;
    @Autowired
    private FishKingDB FishKingDb;
    @Autowired
    private LiKuiFishDeskDao liKuiFishDeskDao;
    @Autowired
    private GoldenCicadaFishDeskDao goldenCicadaFishDeskDao;
    @Autowired
    private ThousandFishDeskDao thousandFishDeskDao;
    @Autowired
    private WaterDeskServiceDao waterDeskServiceDao;

    public Notice noticeList(IoSession session) {
        return this.noticeServiceDao.getNoticeByType();
    }

    public Map<String, Object> getNotice(IoSession session) {
        Map<String, Object> result = new HashMap<>();
        Notice notice = this.noticeServiceDao.getNoticeByType();
        result.put("success", Boolean.TRUE);
        result.put("title", notice.getTitle());
        result.put("content", notice.getContent());
        return result;
    }

    public Map<String, Object> getNotice(int type, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        Notice notice = this.noticeServiceDao.getNoticeByType();
        result.put("success", Boolean.TRUE);
        result.put("type", notice.getType());
        result.put("name", "");
        result.put("title", notice.getTitle());
        result.put("content", notice.getContent());
        return result;
    }

    public Map<String, Object> updateNotice(String title, String content, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        this.noticeServiceDao.updateNotice(title, content);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "修改登录公告", 2, admin.getType(), "Change the landing announcement");
        this.adminLogServiceDao.addAdminLog(adminLog);
        return result;
    }

    public Notice[] getNoticeList(IoSession session) {
        List<Notice> notices = this.noticeServiceDao.getNoticesByType();
        for (Notice n : notices) {
            n.setContent(n.getContent().replaceAll("(\r\n|\r|\n|\n\r)", ""));
            if (n.getRangeType() == 0) {
                n.setRangeStr(MyUtil.getProperties(resultInt(session), "allServerOnline"));
            } else if (n.getRangeType() == 1) {
                n.setRangeStr(MyUtil.getProperties(resultInt(session), "allLianxiDesk"));
            } else if (n.getRangeType() == 2) {
                n.setRangeStr(MyUtil.getProperties(resultInt(session), "allJinjiDesk"));
            } else if (n.getRangeType() == 3) {
                n.setRangeStr(MyUtil.getProperties(resultInt(session), "username") + "：" + n.getUserId());
            }
        }
        return notices.toArray(new Notice[0]);
    }

    /*public static void sendNotice(Notice content) {
        for (Map.Entry<Integer, IoSession> entry : GameParameterAssist.ba.entrySet()) {
            MessageSend.q.notifyAllOperating(new StorageMethodEntity(entry.getValue(), "scrollMessage", new Object[]{content}));
        }
    }*/

    public Map<String, Object> addNotice(Notice notice, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        String content = "";
        String contentEn = "";
        if (notice.getRangeType() == 0) {
            content = "发送了游戏公告，目标全服";
            contentEn = "Send a game announcement to all";
            //大厅
            Map<String,Object> map = new HashMap<>();
            map.put("content", notice.getContent());
            for (Map.Entry<Integer, IoSession> entry : GameParameterAssist.ba.entrySet()) {
                MessageSend.q.notifyAllOperating(new StorageMethodEntity(entry.getValue(), "scrollMessage", new Object[]{map}));
            }
            //子游戏
            List<UserGameTypeSession> userGameTypeSessionList = SessionUtils.getUserGameSession();
            for (UserGameTypeSession userGameTypeSession : userGameTypeSessionList) {
                Set<IoSession> gameSessions = userGameTypeSession.getSessionSet();
                for (Integer userId : userGameTypeSession.getUserGameTypeMap().keySet()) {
                    for (IoSession gameSession : gameSessions) {
                        AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(gameSession, "manageService/sendNotice", new Object[]{userId, notice.getContent()}));
                    }
                }
            }
        } else if (notice.getRangeType() == 1 || notice.getRangeType() == 2) {
            content = "发送了游戏公告，目标欢乐" + (notice.getRangeType() == 1 ? "练习厅" : "竞技厅") + "所有桌";
            contentEn = "Send a game announcement to all tables in " + (notice.getRangeType() == 1 ? "Practice" : "Compete") + " room";
            List<DeskGameType> deskGameTypes = new ArrayList<>();
            int roomId = notice.getRangeType() == 1 ? 1 : 2;
            //狮子
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_0.getType(), deskServiceDao.getDeskIdsByRoomId(roomId)));
            //摇钱树
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_1.getType(), FishKingDb.getDeskIdsByRoomId(roomId)));
            //单挑
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_2.getType(), cardDeskServiceDao.getDeskIdsByRoomId(roomId)));
            //牛魔王
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_3.getType(), bulletFishDeskServiceDao.getDeskIdsByRoomId(roomId)));
            //美人鱼
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_4.getType(), mermaidDeskServiceDao.getDeskIdsByRoomId(roomId)));
            //水浒
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_7.getType(), waterDeskServiceDao.getDeskIdsByRoomId(roomId)));
            //李逵
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_20.getType(), liKuiFishDeskDao.getDeskIdsByRoomId(roomId)));
            //金蟾
            deskGameTypes.add(new DeskGameType(GameTypeEnums.GT_37.getType(), goldenCicadaFishDeskDao.getDeskIdsByRoomId(roomId)));
            for (DeskGameType deskGameType : deskGameTypes) {
                int gameType = deskGameType.getGameType();
                List<Integer> deskIds = deskGameType.getDeskIds();
                for (Integer deskId : deskIds) {
                    DeskUserSession deskUserSession = SessionUtils.getDeskUserSession(deskId, gameType);
                    if (deskUserSession != null) {
                        Set<IoSession> sessionSet = deskUserSession.getSessionSet();
                        List<User> users = deskUserSession.getUsers();
                        if (users != null) {
                            for (User user : users) {
                                for (IoSession ioSession : sessionSet) {
                                    AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(ioSession, "manageService/sendNotice", new Object[]{user.getId(), notice.getContent()}));
                                }
                            }
                        }
                    }
                }
            }
        } else if (notice.getRangeType() == 3) {
            content = "发送了游戏公告，目标会员账号" + notice.getUserId();
            contentEn = "Send a game announcement to member ID:" + notice.getUserId();
            String[] usernames = notice.getUserId().split(";");
            List<User> userList = new ArrayList<>();
            for (String uname : usernames) {
                User user = this.userServiceDao.q_CreateSqlFilter("from User where username=?", new Object[]{uname});
                if (user == null) {
                    result.put("success", Boolean.FALSE);
                    result.put("message", MyUtil.getProperties(resultInt(session), "usernameNotExist"));
                    return result;
                }
                userList.add(user);
            }
            for (User user : userList) {
                List<GameTypeSession> gameTypeSessions = SessionUtils.getSessionByUserId(user.getId());
                for (GameTypeSession gameTypeSession : gameTypeSessions) {
                    for (IoSession ioSession : gameTypeSession.getSessionSet()) {
                        AmfMessageSend.storageMethodOperating.notifyAllOperating(new StorageMethodEntity(ioSession, "manageService/sendNotice", new Object[]{user.getId(), notice.getContent()}));
                    }
                }
            }
        }
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        notice.setType(1);
        notice.setDatetime(MyUtil.dateFormatYMD_HMS_Sting(new Date()));
        notice.setAdmin(admin.getUsername());
        this.noticeServiceDao.saveReturnInteger(notice);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        result.put("newNotice", notice);
        AdminLog adminLog = new AdminLog(admin.getUsername(), content, 2, admin.getType(), contentEn);
        this.adminLogServiceDao.addAdminLog(adminLog);
        return result;
    }

    public Map<String, Object> deleteNotice(int id, IoSession session) {
        Map<String, Object> result = new HashMap<>();
        this.noticeServiceDao.deleteById(id);
        Integer adminId = Integer.valueOf(session.getAttribute("id").toString());
        Admin admin = (Admin) this.adminServiceDao.getById(adminId);
        AdminLog adminLog = new AdminLog(admin.getUsername(), "删除了游戏公告", 2, admin.getType(), "Delete a game announcement");
        this.adminLogServiceDao.addAdminLog(adminLog);
        result.put("success", Boolean.TRUE);
        result.put("message", "");
        return result;
    }

    public void deletePastNotice(String date) {
        this.noticeServiceDao.deletePastNotice(date);
    }

}
